import { Component, OnInit } from '@angular/core';
import { FormControl } from '@angular/forms';
import { Observable } from 'rxjs';
import { startWith, map, debounceTime, distinctUntilChanged, switchMap } from 'rxjs/operators';
import { BookService } from '../book.service';
import { Book } from '../book';
import { Router } from '@angular/router';
import { MatAutocompleteSelectedEvent } from '@angular/material';

@Component({
  selector: 'app-book-search',
  templateUrl: './book-search.component.html',
  styleUrls: ['./book-search.component.css']
})
export class BookSearchComponent implements OnInit {

  myControl: FormControl = new FormControl();

  books$: Observable<Book[]>;

  constructor(private bookService:BookService,
              private router:Router) { }


  ngOnInit() {
    this.books$ = this.myControl.valueChanges
      .pipe(
        startWith(''),
        debounceTime(300),
        distinctUntilChanged(),
        switchMap(val => this.bookService.searchBooks(val))
      );
  }

  jumpBookDetail($event:MatAutocompleteSelectedEvent){
    const bookID = $event.option.value;
    this.router.navigateByUrl("/detail/"+bookID);
  }

}
